package cn.wolfcode.p2p.controller;

import cn.wolfcode.p2p.base.domain.RealAuth;
import cn.wolfcode.p2p.base.domain.UserInfo;
import cn.wolfcode.p2p.base.exception.DisplayableException;
import cn.wolfcode.p2p.base.service.IRealAuthService;
import cn.wolfcode.p2p.base.service.IUserInfoService;
import cn.wolfcode.p2p.base.util.AjaxResult;
import cn.wolfcode.p2p.base.util.RequireLogin;
import cn.wolfcode.p2p.base.util.UserContext;
import cn.wolfcode.p2p.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class RealAuthController {

    @Autowired
    private IRealAuthService realAuthService;
    @Autowired
    private IUserInfoService userInfoService;
    //图片存放的路径
    @Value("${file.path}")
    private String filePath;

    @RequireLogin
    @RequestMapping("/realAuth")
    public String realAuthPage(Model model) {
        UserInfo userInfo = userInfoService.get(UserContext.getCurrent().getId());
        //判断用户是否已经是实名认证了
        if(userInfo.isHasRealAuth()){
            //如果已经实名认证了 则应该跳转界面到realAuth_result 设置auditing为false
            model.addAttribute("auditing",false);
            //并共享realAuth数据
            model.addAttribute("realAuth",realAuthService.get(userInfo.getRealAuthId()));
            return "realAuth_result";
        }else{
            //如果没有实名认证
            //判断userInfo中realAuthId 是否为null
            if(userInfo.getRealAuthId() == null){
                //如果为null 则表示没有申请过 跳转到界面realAuth
                return "realAuth";
            }else {
                //如果已经提交申请了 则把auditing设置为true 和 跳转界面realAuth_result
                model.addAttribute("auditing",true);
                return "realAuth_result";
            }
        }
    }

    @RequestMapping("/realAuth_save")
    @ResponseBody
    public AjaxResult realAuthSave(RealAuth realAuth) {
        AjaxResult result = null;
        try {
            //提交申请
            realAuthService.apply(realAuth);
            result = new AjaxResult();
        } catch (DisplayableException e) {
            e.printStackTrace();
            //如果底层是抛出这个异常的话 则把 异常信息显示给用户看
            result = new AjaxResult(false, e.getMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
            //把异常信息写入到日志中
            result = new AjaxResult(false, "系统异常,程序员哥哥正在努力抢救中...");
        }
        return result;
    }

    /**
     * 上传图片文件
     * @param file 图片文件
     * @return
     */
    @RequestMapping("/uploadImage")
    @ResponseBody
    public String uploadImage(MultipartFile file){
        String imagePath = UploadUtil.upload(file, filePath);
        return imagePath;
    }
}
